package com.turing.post.common.impl;

import java.math.BigInteger;
import java.util.List;

import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.turing.post.common.util.SysOpUser;
import com.turing.post.common.util.SysOpUserDao;
import com.turing.post.util.Config;
import com.turing.post.util.GeneralDao;
import com.turing.post.util.PCPSApplicationException;
import com.turing.post.util.PCPSUtil;
import com.turing.post.util.PCPSWebInput;

/**
 * @author 张小盼
 * 
 */
@Stateless(mappedName = "common.impl.SysOpUserDaoImpl")
@Remote
@Local
public class SysOpUserDaoImpl implements SysOpUserDao {

	// @EJB(mappedName = "common.impl.SysOperLogDaoImpl")
	// private SysOperLogDao sysOperLogDaoImpl;
	/**
	 * 实体管理器
	 */
	@PersistenceContext
	protected EntityManager _em;

	public SysOpUser getSysOpUserByOperId(BigInteger operId) {
		return _em.find(SysOpUser.class, operId);
	}

	@SuppressWarnings("unchecked")
	public SysOpUser getSysOpUserByOperLogonName(String operLogonName) {
		String jpql = "select * from SysOpUser c where c.operLogonName = ?1";
		Query query = _em.createNativeQuery(jpql, SysOpUser.class)
				.setParameter(1, operLogonName);
		List<SysOpUser> list = query.getResultList();
		if (list == null || list.isEmpty() || list.size() < 1) {
			return null;
		}
		return list.get(0);
	}

	public SysOpUser getQuestionByByOperLogonName(String operLogonName) {
		SysOpUser sou = getSysOpUserByOperLogonName(operLogonName);
		if (sou == null) {
			return null;
		} else {
			SysOpUser _return = new SysOpUser();
			_return.setOperId(sou.getOperId());
			_return.setQuestion1(sou.getQuestion1());
			_return.setQuestion2(sou.getQuestion2());
			_return.setAnswer3(sou.getQuestion3());
			return _return;
		}
	}

	@Override
	public void deleteSysOpUser(BigInteger operId)
			throws PCPSApplicationException {
		// 删除日志
		try {
			// sysOperLogDaoImpl.deleteSysOperLogByOperId(null, operId);
			String sql = "delete from sysopuser where operid=" + operId;
			Query query = _em.createNativeQuery(sql);
			query.executeUpdate();
		} catch (Exception e) {
			throw new PCPSApplicationException(
					PCPSApplicationException.ERRCODE_CATEGORY_DATABASE,
					"delete","该用户已被引用，禁止删除!" , false);//e.getMessage()
		}
	}

	@Override
	public BigInteger getMaxOperId() {
		Query query = _em
				.createNativeQuery("select nvl(max(operId),0)+1 operId from SysOpUser t");
		return new BigInteger(query.getSingleResult().toString());
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<SysOpUser> getSysOpUserList(PCPSWebInput webInput,
			String branchNo, String status, Integer page) {
		int maxResult = Config.PAGE_SIZE;
		int startPosition = maxResult * page;
		if(page==-1){
			maxResult = 36000;
			startPosition = 0;
		}
		String sql = "select * from SysOpUser t where operbranchno is not null and IssueOper =0 and InternetAgent =0 and (?1 is null or Status=?1)";
		sql += getFirstSQL(webInput, branchNo);
		sql = sql + " order by operId";
		Query query = _em.createNativeQuery(sql, SysOpUser.class)
				.setFirstResult(startPosition).setMaxResults(maxResult);
		query.setParameter(1, status);
		return query.getResultList();
	}

	@Override
	public BigInteger getSysOpUserTotal(PCPSWebInput webInput, String branchNo,
			String status) {
		String sql = "select nvl(count(*),0) from SysOpUser t where operbranchno is not null and IssueOper =0 and InternetAgent =0 and (?1 is null or Status=?1)";
		sql += getFirstSQL(webInput, branchNo);
		Query query = _em.createNativeQuery(sql);
		query.setParameter(1, status);
		return new BigInteger(query.getSingleResult().toString());
	}

	/**
	 * 判断是查询单个还是归属机构下所有
	 * 
	 * @param sql
	 * @param webInput
	 * @return
	 */
	private String getFirstSQL(PCPSWebInput webInput, String branchNo) {
		// 第一次选择菜单查询
		if (PCPSUtil.isEmpty(branchNo)) {
			if (!PCPSUtil.isEmpty(webInput.getOperBranchNo())) {
				branchNo = webInput.getOperBranchNo();
			}
		}
		if (!PCPSUtil.isEmpty(branchNo)) {
			if (webInput.isAll()) {
				return " and OperBranchNo in (select subBranchNo from sysbranchsubord t where t.branchno='"
						+ branchNo + "')";
			} else {
				return " and OperBranchNo ='" + branchNo + "'";
			}
		} else {
			return " and 0!=0";
		}
	}

	@Override
	public void insertSysOpUserInfo(SysOpUser sysOpUser)
			throws PCPSApplicationException {
		GeneralDao.insert(_em, sysOpUser);
	}

	@Override
	public void updateSysOpUserInfo(SysOpUser sysOpUser)
			throws PCPSApplicationException {
		GeneralDao.update(_em, sysOpUser);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<SysOpUser> getSysAndIssueSysOpUserList(boolean isSysBranch,
			Integer page) {
		int maxResult = Config.PAGE_SIZE;
		int startPosition = maxResult * page;
		String sql = "";
		if (isSysBranch) {
			sql = "select * from SysOpUser c where c.OperBranchNo is not null and IssueOper = 1 and InternetAgent =0 order by operBranchNo";
		} else {
			sql = "select * from SysOpUser c where c.OperBranchNo is null and IssueOper = 0 and  InternetAgent =0 order by operBranchNo";
		}
		Query query = _em.createNativeQuery(sql, SysOpUser.class)
				.setFirstResult(startPosition).setMaxResults(maxResult);
		return query.getResultList();
	}

	@Override
	public BigInteger getSysAndIssueSysOpUserTotal(boolean isSysBranch) {
		String sql = "";
		if (isSysBranch) {
			sql = "select nvl(count(*),0) from SysOpUser c where c.OperBranchNo is not null and IssueOper = 1 and InternetAgent =0";
		} else {
			sql = "select nvl(count(*),0) from SysOpUser c where c.OperBranchNo is null and IssueOper = 0 and  InternetAgent =0";
		}
		Query query = _em.createNativeQuery(sql);
		return new BigInteger(query.getSingleResult().toString());
	}

	@SuppressWarnings("unchecked")
	@Override
	public SysOpUser getInternetAgentSysOpUserByIssueCompany(
			String issueCompanyNo) {
		String sql = "select * from SysOpUser t where InternetAgent = 1 and OperBranchNo = ?1";
		Query query = _em.createNativeQuery(sql, SysOpUser.class);
		query.setParameter(1, issueCompanyNo);
		List<SysOpUser> souList = query.getResultList();
		if (souList.size() > 0) {
			return souList.get(0);
		} else {
			return null;
		}
	}
}
